package com.example.demo.service.iml;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.mapper.SubscriptionMapper;
import com.example.demo.model.entity.SubscriptionEntity;
import com.example.demo.service.SubscriptionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class SubscriptionServiceImpl extends ServiceImpl<SubscriptionMapper, SubscriptionEntity> implements SubscriptionService {
    private static final Logger log = LoggerFactory.getLogger(SubscriptionServiceImpl.class);

    @Override
    @Transactional(readOnly = true)
    public SubscriptionEntity findByOpenIdAndDeviceId(String openId, String deviceId) {
        // 遮盖部分敏感信息用于日志
        String maskedOpenId = maskSensitiveInfo(openId);
        log.debug("开始查询订阅信息 - OpenId: {}, DeviceId: {}", maskedOpenId, deviceId);

        LambdaQueryWrapper<SubscriptionEntity> queryWrapper = new LambdaQueryWrapper<SubscriptionEntity>()
                .eq(SubscriptionEntity::getOpenId, openId)
                .eq(SubscriptionEntity::getDeviceId, deviceId);

        SubscriptionEntity result = this.getOne(queryWrapper);

        if (result == null) {
            log.debug("未找到匹配的订阅信息");
        } else {
            log.debug("找到订阅信息 - ID: {}, 订阅状态: {}", result.getId(), result.getSubscribed());
        }

        return result;
    }

    @Override
    @Transactional
    public void cleanupExpiredSubscriptions() {
        LocalDateTime now = LocalDateTime.now();

        LambdaQueryWrapper<SubscriptionEntity> queryWrapper = new LambdaQueryWrapper<SubscriptionEntity>()
                .eq(SubscriptionEntity::getSubscribed, true)
                .lt(SubscriptionEntity::getExpireTime, now);

        List<SubscriptionEntity> expiredSubscriptions = this.list(queryWrapper);

        if (expiredSubscriptions.isEmpty()) {
            log.info("没有找到过期的订阅");
            return;
        }

        log.info("找到{}个过期订阅，准备更新状态", expiredSubscriptions.size());

        for (SubscriptionEntity subscription : expiredSubscriptions) {
            subscription.setSubscribed(false);
            this.updateById(subscription);
            log.debug("已将订阅ID:{}标记为未订阅（已过期）", subscription.getId());
        }

        log.info("过期订阅清理完成");
    }

    /**
     * 遮盖敏感信息用于日志记录
     */
    private String maskSensitiveInfo(String info) {
        if (info == null || info.length() <= 8) {
            return "***";
        }
        int visibleChars = 4;
        return info.substring(0, visibleChars) + "***" +
                info.substring(info.length() - visibleChars);
    }
}